<template>
  <div class="alarmConfiguration zy-content">
    <!-- 模具与产品 -->
    <search :columns="searchData" @getSearch="getSearch"></search>
    <div class="alarmConfiguration">
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">{{ $t("common.listInformation") }}</span>
        </div>
        <div class="tableContent">
          <Table
            class="resizable-table"
            border
            @on-column-width-resize="onColumnWidthResize"
            :columns="columnsList"
            ellipsis
            ref="selection"
            stripe
            :data="dataArr"
            @on-selection-change="onSelectChange"
          >
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="getDeviceList(row)">关联产品</span>
            </template>
          </Table>
        </div>
        <!-- 分页 -->
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="delIds.length" />
          <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="pageSizeOption"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
          />
        </div>
      </div>
    </div>
    <!-- 已经关联产品列表 -->
    <Modal
      :mask-closable="false"
      v-model="create"
      title="关联产品"
      class="modal-content-layout"
      width="70%"
    >
      <search :columns="searchData1" @getSearch="getSearch1" :span="6" ref="search1"></search>
      <div class="btns clear btn-box">
        <Button @click="getNoList()">选择产品</Button>
        <Button @click="delRowBetch" v-has="'moldLedgerBatchDelBtn'">
          {{
          $t("common.batchDelete")
          }}
        </Button>
        <Button @click="linkBoth(true)" :disabled="delIds1.length < 2">关联产品组</Button>
        <Button @click="linkBoth(false)" :disabled="delIds1.length < 2">取消同组标识</Button>
      </div>
      <div class="alarmConfiguration">
        <div class="list-layout">
          <!-- 表格 -->
          <div class="tableContent mt14">
            <Table
              class="resizable-table"
              border
              :columns="columns1"
              ellipsis
              ref="selection"
              stripe
              :data="dataArr1"
              @on-selection-change="onSelectChange1"
              @on-column-width-resize="onColumnWidthResize"
            >
              <template slot-scope="{ row }" slot="action">
                <span class="operationBtn" @click="handleEdit(row)">
                  <i class="iconfont zy-common-bianji"></i>
                  {{ $t("common.Edit") }}
                </span>
                <span class="operationBtn" @click="delRow(row)">
                  <i class="iconfont zy-common-shanchu"></i>
                  {{ $t("common.Delete") }}
                </span>
              </template>
            </Table>
          </div>
          <!-- 分页 -->
          <div class="pageWrap mt16">
            <pageLeftTitle :total="total1" :selected="delIds1.length" />
            <Page
              :total="total1"
              :page-size="pageSize1"
              :page-size-opts="pageSizeOption"
              :current="pageNum1"
              @on-change="changePageNum1"
              @on-page-size-change="changePageSize1"
              show-sizer
              show-total
            />
          </div>
        </div>
      </div>
    </Modal>
    <Modal
      :mask-closable="false"
      v-model="deviceCategoryShow"
      title="编辑"
      class="modal-content-layout"
      width="30%"
    >
      <div class="addProject">
        <Form
          ref="form"
          class="formList"
          :model="formItem"
          label-position="top"
          :rules="{
            realityCavityNum: [
              {
                required: true,
                message: '请输入实际使用型腔数',
                trigger: 'blur',
                type: 'number',
              },
            ],
            standardCavityNum: [
              {
                required: true,
                message: '请输入标准型腔数',
                trigger: 'blur',
                type: 'number',
              },
            ],
            dataAcquisitionRate: [
              {
                required: true,
                message: '请输入数采系数',
                trigger: 'blur',
                type: 'number',
              },
            ],
          }"
        >
          <Row :gutter="20">
            <Col span="24">
              <FormItem label="标准型腔数" prop="standardCavityNum">
                <InputNumber
                  type="numble"
                  onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                  v-model="formItem.standardCavityNum"
                  :placeholder="`${$t('common.inputInfo')}`"
                />
                <!-- <Input type="number" @on-keyup="keyUp($event, 'standardCavityNum', true)" v-model="formItem.standardCavityNum"
                :placeholder="`${$t('common.inputInfo')}`">
                </Input>-->
              </FormItem>
              <FormItem label="实际使用型腔数" prop="realityCavityNum">
                <InputNumber
                  type="numble"
                  onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                  v-model="formItem.realityCavityNum"
                  :placeholder="`${$t('common.inputInfo')}`"
                />
              </FormItem>
              <FormItem label="数采系数" prop="dataAcquisitionRate">
                <InputNumber
                  type="numble"
                  onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
                  v-model="formItem.dataAcquisitionRate"
                  :placeholder="`${$t('common.inputInfo')}`"
                />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <div slot="footer">
        <Button type="default" @click="deviceCategoryShow = false">
          {{
          $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" @click="editDeviceCategory('form')">
          {{
          $t("maintenance.Confirmed")
          }}
        </Button>
      </div>
    </Modal>
    <!-- 关联产品列表 -->
    <Modal
      :mask-closable="false"
      v-model="createLink"
      title="关联产品"
      class="modal-content-layout"
      width="65%"
    >
      <search :columns="searchData1" @getSearch="getSearch2(arguments)" ref="search2" :span="8"></search>
      <div class="alarmConfiguration">
        <div class="list-layout2">
          <!-- 表格 -->
          <div class="tableContent mt14">
            <!-- {{ dataArr2 }}{{ delIds2 }} -->
            <Table
              class="resizable-table"
              border
              @on-column-width-resize="onColumnWidthResize"
              :columns="columns2"
              ellipsis
              ref="selection"
              stripe
              :data="dataArr2"
              @on-selection-change="onSelectChange2"
            ></Table>
          </div>
          <!-- 分页 -->
          <div class="pageWrap mt16">
            <pageLeftTitle :total="total2" :selected="delIds2.length" />
            <Page
              :total="total2"
              :page-size="pageSize2"
              :page-size-opts="pageSizeOption"
              :current="pageNum2"
              @on-change="changePageNum2"
              @on-page-size-change="changePageSize2"
              show-sizer
              show-total
            />
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button type="default" @click="createLink = false">
          {{
          $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" :loading="loading" @click="linkEq">关联产品</Button>
      </div>
    </Modal>
    <!-- 请确认是否删除弹框 -->
    <Modal
      :mask-closable="false"
      v-model="delFaultCodeShowF"
      :title="$t('common.Delete')"
      class="modal-title-layout"
    >
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t("common.confirmDelete") }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">
          {{
          $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" :loading="loading" @click="deleteOk">
          {{
          $t("maintenance.Confirmed")
          }}
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  searchApi,
  getLinkList,
  getDeviceNoList,
  deleteApi,
  devicesAssociated
} from "@/api/moldManagement/mpLink.js";

import search from "@/components/curd/searchList.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "mpLink",
  components: { search },
  mixins: [toggleTableOperation],
  data() {
    return {
      //一级搜索
      searchData: [
        {
          title: "模具名称",
          key: "moldName"
        },
        {
          title: "模具编号",
          key: "moldCode"
        },
        {
          title: "是否关联产品",
          key: "productsNumber",
          type: "select",
          dicData: [
            {
              label: "未关联",
              value: "0"
            },
            {
              label: "已关联",
              value: "1"
            }
          ]
        },
        {
          title: "模具等级",
          key: "moldGrade",
          type: "select",
          dicData: [
            {
              label: "A",
              value: "A"
            },
            {
              label: "B",
              value: "B"
            },
            {
              label: "C",
              value: "C"
            }
          ]
        }
      ],
      searchData1: [
        {
          title: "产品型号",
          key: "materialModel",
          span:6,
          // dicUrl: "/basic/organization/findListByToken?level=0",
          // type: "cascader",
          // params: {
          //   label: "name",
          //   value: "code",
          //   children: "children",
          // },
        },
        {
          title: "产品编号",
          key: "materialCode",
          span:6,

        },
        {
          title: "产品名称",
          key: "materialName",
          span:6,

        }
      ],
      searchData2: [
        {
          title: "所在位置",
          type: "cascader",
          key: "installPosition",
          dicUrl: "/basic/organization/findListByToken?level=0",
          params: {
            label: "name",
            value: "code",
            children: "children"
          }
        },
        {
          title: "设备编号",
          key: "deviceNo"
        }
      ],
      //一级table配置
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "资产编号",
          key: "assetCode",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "模具编号",
          key: "moldCode",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "模具名称",
          key: "moldName",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "模具类型",
          key: "moldModel",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "模具等级",
          key: "moldGrade",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "备注",
          key: "remake",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "关联产品数量",
          key: "productsRecordCount",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "操作时间",
          key: "moldMaterialTime",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "操作人",
          key: "moldMaterialOperator",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 180,
          align: "center"
        }
      ],
      columns1: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "产品编号",
          key: "materialCode",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "产品型号",
          key: "materialModel",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "产品名称",
          key: "materialName",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "型腔数",
          key: "cavityNum",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "标准型腔数",
          key: "standardCavityNum",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "实际使用型腔数",
          key: "realityCavityNum",
          minWidth: 150,
          align: "center",
          resizable: true,
          tooltip: true
          // render: (h, params) => {
          //   return h("div", [
          //     h("InputNumber", {
          //       props: {
          //         min: 0,
          //         max: 999999,
          //         value: params.row.deviceCategory || null,
          //       },
          //       on: {
          //         // 编辑数量的时候,触发的事件
          //         "on-change": (e) => {
          //           params.row.deviceCategory = e;
          //           this.dataArr1[params.index] = params.row;
          //           this.delIds1.forEach((v, index) => {
          //             if (v.id == params.row.id) {
          //               this.delIds1.splice(index, "", params.row);
          //             }
          //           });
          //           this.materialIdList[params.index].totalActualCavity = e;
          //         },
          //       },
          //     }),
          //   ]);
          // },
        },
        {
          title: "数采系数",
          key: "dataAcquisitionRate",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "成型周期",
          key: "moldingCycle",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "同组标识",
          key: "identification",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 180,
          align: "center"
        }
      ],
      columns2: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "产品编号",
          key: "materialCode",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "产品型号",
          key: "materialModel",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: "产品名称",
          key: "materialName",
          minWidth: 100,
          align: "center",
          resizable: true,
          tooltip: true
        }
      ],
      moldCode: "",
      id: "",

      loading: false,
      loading1: false,
      loading2: false,
      // 一级二级弹窗显示
      create: false,
      createLink: false,
      //三级搜索参数
      searchParams: {},
      searchParams1: {},
      searchParams2: {},
      //一级页面分页参数
      pageNum: 1,
      pageSize: 10,
      total: 0,
      //二级页面分页参数
      pageNum1: 1,
      pageSize1: 10,
      total1: 0,
      formItem: {
        realityCavityNum: 1,
        standardCavityNum: 1,
        dataAcquisitionRate: 1
      },
      //三级页面分页参数
      pageNum2: 1,
      pageSize2: 10,
      total2: 0,
      //一级table列表数据
      dataArr: [],
      dataArr1: [],
      dataArr2: [],

      backupList: [],
      shelfList: [],
      locationList: [],
      allCheck: false,

      delFaultCodeShowF: false, //是否显示删除弹窗
      deviceCategoryShow: false,
      realityCavityNumRow: {},
      pageSizeOption: [10, 20, 30, 40],
      delIds: [],
      delIds1: [],
      delIds2: [],
      selection: [],
      createByOptions: []
    };
  },
  mounted() {
    this.getTableColumnsWidth(this.columns);
    this.searchList();
  },
  methods: {
    keyUp(e, key, money) {
      // 如果是删除为空 则不处理
      if (!this.formItem[key]) {
        return (this.formItem[key] = "");
      }
      // 每次抬键处理,对应金额渲染两位小数||数字
      let num = "";
      if (money) {
        num = this.formItem[key].match(/^\d*(\.?\d{0,0})/g)[0];
      } else {
        num = this.formItem[key].replace(/^[^\d]+$/g, "").split(".")[0];
      }
      this.formItem[key] = `${num}`;
    },
    editDeviceCategory(name) {
      this.$refs[name].validate(valid => {
        if (!valid) {
          return;
        } else {
          this.axios({
            method: "put",
            url: "/dms/moldMaterial/setRealityCavityNum",
            data: {
              ...this.realityCavityNumRow,
              ...this.formItem
            }
          }).then(res => {
            if (res.code === 200) {
              this.searchList1();
              this.$Message.success(res.msg);
              this.deviceCategoryShow = false;
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true
              });
            }
          });
        }
      });
    },
    linkBoth(state) {
      // let data = {
      //   id: this.id,
      //   moldCode: this.moldCode,
      //   materialIdList: this.materialIdList
      // }
      if (state == true) {
        this.axios({
          method: "POST",
          url: "/dms/moldMaterial/identification",
          data: this.delIds1
        }).then(res => {
          if (res.code === 200) {
            this.searchList1();
            this.$Message.success({
              content: res.msg,
              duration: 6,
              closable: true
            });
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      } else {
        this.axios({
          method: "POST",
          url: "/dms/moldMaterial/groupIdentification",
          data: this.delIds1
        }).then(res => {
          if (res.code === 200) {
            this.searchList1();
            this.$Message.success({
              content: res.msg,
              duration: 6,
              closable: true
            });
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      }
    },
    getSearch(arg) {
      this.searchParams = arg || {};
      this.delIds = [];
      this.changeNum();
    },
    getSearch1(arg) {
      this.searchParams1 = arg || {};
      this.delIds1 = [];
      this.changeNum1();
    },
    getNoList() {
      this.$refs.search2.reset();
    },
    getSearch2(arg) {
      this.searchParams2 = JSON.parse(JSON.stringify(arg[0])) || {};
      this.delIds2 = [];
      this.changeNum2();
    },
    getDeviceList(row) {
      this.delIds = [];
      this.delIds1 = [];
      this.delIds2 = [];
      this.moldCode = row.moldCode;
      this.id = row.id;
      this.$refs.search1.reset();
      this.searchList1();
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    // 2
    changeNum1() {
      this.pageNum1 = 1;
      this.searchList1();
    },
    changePageSize1(pageSize) {
      this.pageSize1 = pageSize;
      this.searchList1();
    },
    changePageNum1(val) {
      this.pageNum1 = val;
      this.searchList1();
    },
    handleEdit(row) {
      this.realityCavityNumRow = row;
      this.formItem.realityCavityNum = row.realityCavityNum;
      this.formItem.dataAcquisitionRate = row.dataAcquisitionRate;
      this.formItem.standardCavityNum = row.standardCavityNum;
      this.deviceCategoryShow = true;
    },
    // 3
    changeNum2() {
      this.pageNum2 = 1;
      this.searchList2();
    },
    changePageSize2(pageSize) {
      this.pageSize2 = pageSize;
      this.searchList2();
    },
    changePageNum2(val) {
      this.pageNum2 = val;
      this.searchList2();
    },

    //查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        productsNumber: this.searchParams.productsNumber || "2"
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      searchApi(params).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.records;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    //查询列表
    searchList1() {
      this.create = true;

      let params = {
        pageNum: this.pageNum1,
        pageSize: this.pageSize1,
        moldCode: this.moldCode
      };
      for (let key in this.searchParams1) {
        if (this.searchParams1[key]) {
          this.$set(params, key, this.searchParams1[key]);
        }
      }
      getLinkList(params).then(res => {
        if (res.code === 200) {
          this.dataArr1 = res.data.records;
          this.total1 = res.data.total;
          this.create = true;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
        // this.dataArr1=[{},{},{} ]
      });
    },
    //查询列表
    searchList2() {
      let params = {
        pageNum: this.pageNum2,
        pageSize: this.pageSize2,
        moldCode: this.moldCode
      };
      for (let key in this.searchParams2) {
        if (this.searchParams2[key]) {
          this.$set(params, key, this.searchParams2[key]);
        }
      }
      getDeviceNoList(params).then(res => {
        if (res.code === 200) {
          this.dataArr2 = res.data.records;
          this.total2 = res.data.total;
          this.createLink = true;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
      // this.total2 = 6;
      // this.dataArr2 = [{}, {}, {}, {}, {}, {}];
    },
    //勾选列表
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item, index) => {
        myArray.push(item.id);
      });
      this.delIds = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    //勾选列表
    onSelectChange1(selection) {
      let myArray = [];
      let materialIdList = [];
      selection.map((item, index) => {
        myArray.push(item.id);
      });
      selection.map((item, index) => {
        materialIdList.push({
          id: item.id,
          totalActualCavity: item.deviceCategory
        });
      });
      this.materialIdList = materialIdList;
      this.delIds1 = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    }, //勾选列表
    onSelectChange2(selection) {
      this.delIds2 = selection;
    },
    //批量删除
    delRowBetch() {
      if (this.delIds1.length == 0) {
        this.$Message.warning({
          content: `${this.$t("common.deleteItems")}`,
          duration: 6,
          closable: true
        });
        return;
      } else {
        this.delFaultCodeShowF = true;
      }
    },
    //删除
    delRow(row) {
      //点击展示提示删除弹窗
      this.delFaultCodeShowF = true;
      this.delIds1 = [];
      this.delIds1.push(row.id);
    },
    deleteOk() {
      this.loading = true;
      // let params = { deviceIdList: this.delIds1, moldId: this.id };
      deleteApi(this.delIds1).then(res => {
        this.loading = false;
        this.changeNum();
        this.changeNum1();
        if (res.code === 200) {
          this.changeNum1();
          this.$Message.success("删除成功");
          this.$refs.selection.selectAll(false);
          this.delFaultCodeShowF = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    linkEq() {
      this.loading = true;
      let materialIdList = this.delIds2.map(item => ({
        materialId: item.id,
        productTime: item.productTime,
        materialActual: item.materialActual,
        materialCavities: item.materialCavities
      }));
      let params = { materialIdList, moldId: this.id };
      devicesAssociated(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$Message.success("关联成功");
          this.$refs.selection.selectAll(false);
          this.changeNum();
          this.changeNum1();
          this.createLink = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.ivu-input-number {
  width: -webkit-fill-available;
}

.btn-box {
  padding: 8px 5px !important;
}
</style>
